package routers

import (
	"data_summary/common/app"
	_ "data_summary/common/statik"
	"github.com/go-macaron/gzip"
	"github.com/go-macaron/toolbox"
	"github.com/rakyll/statik/fs"
	logger "github.com/sirupsen/logrus"
	"gopkg.in/macaron.v1"
	"io"
	"log"
	"net/http"
)

const (
	urlPrefix = "/api"
	staticDir = "public"
)

var statikFS http.FileSystem

func init() {
	var err error
	statikFS, err = fs.New()
	if err != nil {
		log.Fatal(err)
	}
}

// Register 路由注册
func Register(m *macaron.Macaron) {
	m.SetURLPrefix(urlPrefix)
	// 所有GET方法，自动注册HEAD方法
	m.SetAutoHead(true)
	m.Get("/", func(ctx *macaron.Context) {
		file, err := statikFS.Open("/index.html")
		if err != nil {
			logger.Error("读取首页文件失败: %s", err)
			ctx.WriteHeader(http.StatusInternalServerError)
			return
		}

		io.Copy(ctx.Resp, file)

	})

	// 404错误
	m.NotFound(func(ctx *macaron.Context) string {
		jsonResp := app.JsonResponse{}

		return jsonResp.Failure(app.NotFound, "您访问的页面不存在")
	})
	// 50x错误
	m.InternalServerError(func(ctx *macaron.Context) string {
		jsonResp := app.JsonResponse{}

		return jsonResp.Failure(app.ServerError, "服务器内部错误, 请稍后再试")
	})
}

// 中间件注册
func RegisterMiddleware(m *macaron.Macaron) {
	m.Use(macaron.Logger())
	m.Use(macaron.Recovery())
	if macaron.Env != macaron.DEV {
		m.Use(gzip.Gziper())
	}
	m.Use(
		macaron.Static(
			"",
			macaron.StaticOptions{
				Prefix:     staticDir,
				FileSystem: statikFS,
			},
		),
	)
	if macaron.Env == macaron.DEV {
		m.Use(toolbox.Toolboxer(m))
	}
	m.Use(macaron.Renderer())
	//m.Use(checkAppInstall)
	//m.Use(ipAuth)
	//m.Use(userAuth)
	//m.Use(urlAuth)
}
